const express = require('express');
const WebSocket = require('ws');
const RDP = require('node-rdpjs');
const app = express();
const server = require('http').createServer(app);
const wss = new WebSocket.Server({ server });

const winston = require('winston');
const logger = winston.createLogger({
    level: 'info',
    format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.printf((info => `${info.level}: ${info.message}`))
    )
});

// RDP连接处理模块
function handleRDPConnection(ws, serverIp, serverPort, username, password) {
    const rdpClient = RDP.createClient({
        hostname: serverIp,
        port: parseInt(serverPort),
        username: username,
        password: password,
        screen: { width: 1024, height: 768 }
    });

    rdpClient.on('connect', () => {
        logger.info('Connected to RDP server');
    });

    rdpClient.on('bitmap', (bitmap) => {
        ws.send(bitmap);
    });

    rdpClient.on('error', (err) => {
        logger.error('RDP error:', err);
        ws.close();
        if (err.code === 'ECONNREFUSED') {
            ws.send(JSON.stringify({ type: 'error', message: 'RDP服务器拒绝连接，请检查服务器地址和端口。' }));
        } else {
            ws.send(JSON.stringify({ type: 'error', message: `RDP连接错误: ${err.message}` }));
        }
    });

    return rdpClient;
}

wss.on('connection', (ws, req) => {
    const url = new URL(req.url, `http://${req.headers.host}`);
    const serverIp = url.searchParams.get('server');
    const serverPort = url.searchParams.get('port') || 3389;
    const username = url.searchParams.get('username') || '';
    const password = url.searchParams.get('password') || '';

    logger.info(`Connecting to RDP server: ${serverIp}:${serverPort}`);

    const rdpClient = handleRDPConnection(ws, serverIp, serverPort, username, password);

    ws.on('message', (event) => {
        try {
            const message = JSON.parse(event.data);
            if (message.type === 'keydown') {
                rdpClient.sendKeyboardEvent(message.key);
            } else if (message.type ==='mousedown' || message.type ==='mouseup' || message.type ==='mousemove') {
                rdpClient.sendMouseEvent(message.type, message.x, message.y);
            } else if (message.type === 'paste') {
                // 实现粘贴逻辑，这里简单打印接收到的内容
                console.log('接收到粘贴内容:', message.text);
                // 这里需要根据RDP协议实现具体的粘贴处理
            } else if (message.type ==='resolution') {
                // 更新RDP客户端的分辨率设置
                rdpClient.screen.width = message.width;
                rdpClient.screen.height = message.height;
                // 发送分辨率更改确认消息给客户端
                ws.send(JSON.stringify({ type:'resolution_confirm' }));
            }
        } catch (e) {
            logger.error('Error parsing message:', e);
        }
    });

    ws.on('close', () => {
        logger.info('Client disconnected');
        rdpClient.disconnect();
    });
});

server.listen(8081, () => {
    logger.info('Server running at http://localhost:8081');
});
